const mongoose = require('mongoose');//引用mongoose
mongoose.connect('mongodb://localhost/school');//连接school数据库

const express = require('express');
const app = express();
const port = 3000;


const db = mongoose.connection;
db.on('erroe', console.error.bind(console, 'connection error'));
db.once('open', () => {
    console.log('MongoDB 连接成功！ ')
});

const studentSchema = mongoose.Schema({
    name: String,
    hobby: String,
    age: Number
});

const student = mongoose.model('student', studentSchema);

// student.find({},(err,result) => {
//     if(err) return console.error(err.message);
//     console.log(result);
// });

// student.update({ name: '王五' }, { $set: { age: 33 } }, (err, result) => {
//     if (err) {
//         return console.error(err);
//     }
//     // console.log(result);
//     // result:  { n:1,nModified: 1,ok: 1}
//     if (result.ok > 0) {
//         console.log('修改成功');
//     }
// });


//当用户请求 /addStudent/:name时：
app.get('/addStudent/:name', (req, res) => {
    const name = req.params.name;
    // 将接受到的name参数存库
 
    student.create({ name: name }, (err, result) => {
        if (err) {
            return res.send(err.message);
        }
        res.send('新增成功： ' + name);
    });
});

app.listen(port, () => {
    console.log('服务器启动成功，监听端口：', port);
})